package com.wave.wavesystem.business.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wave.wavesystem.business.mapper.DeptMapper;
import com.wave.wavesystem.business.pojo.entity.DeptEntity;
import com.wave.wavesystem.business.pojo.entity.MenuEntity;
import com.wave.wavesystem.business.pojo.vo.DeptVO;
import com.wave.wavesystem.business.service.DeptService;
import com.wave.wavesystem.common.util.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 夕下风波
 * @date 2025-01-23
 * @description 部门表 业务层接口
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptEntity> implements DeptService {

    @Override
    public List<DeptVO> allDept() {
        QueryChain<DeptEntity> queryChain = QueryChain.of(DeptEntity.class)
                .isNull(DeptEntity::getParentId);
        List<DeptEntity> parentDepts = this.list(queryChain);
        if (Func.isEmpty(parentDepts)) return Collections.emptyList();
        return fillDept(parentDepts);
    }

    /**
     * 获取全部部门
     *
     * @param parentDepts 父级部门
     */
    private List<DeptVO> fillDept(List<DeptEntity> parentDepts) {
        List<DeptVO> allDept = new ArrayList<>();
        for (DeptEntity parentDept : parentDepts) {
            DeptVO deptVO = new DeptVO();
            BeanUtils.copyProperties(parentDept, deptVO);
            allDept.add(deptVO);
            List<DeptEntity> childrenDepts = this.list(QueryChain.of(DeptEntity.class)
                    .eq(DeptEntity::getParentId, parentDept.getId()));
            if (Func.isEmpty(childrenDepts)) continue;
            List<DeptVO> childrenDept = fillDept(childrenDepts);
            deptVO.setChildren(childrenDept);
        }
        return allDept;
    }
    /**
     * 获取全部部门
     *
     * @param parentDeptIds 父级部门id
     */
    @Override
    public List<Long> findBelongsDept(List<Long> parentDeptIds) {
        List<Long> allDept = new ArrayList<>();
        for (Long parentDeptId : parentDeptIds) {
            allDept.add(parentDeptId);
            List<DeptEntity> childrenDepts = this.list(QueryChain.of(DeptEntity.class)
                    .eq(DeptEntity::getParentId, parentDeptId));
            if (Func.isEmpty(childrenDepts)) continue;
            List<Long> ids = childrenDepts.stream().map(DeptEntity::getId).toList();
            List<Long> childrenDept = findBelongsDept(ids);
            allDept.addAll(childrenDept);
        }
        return allDept;
    }


}
